package com.example.common.util;

import lombok.experimental.UtilityClass;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@UtilityClass
public class TreeUtils {

    /**
     * 构建树形结构
     */
    public <T extends TreeNode<T>> List<T> buildTree(List<T> nodes) {
        if (CollectionUtils.isEmpty(nodes)) {
            return new ArrayList<>();
        }

        // 按父ID分组
        Map<Long, List<T>> childrenMap = nodes.stream()
                .filter(node -> node.getParentId() != 0)
                .collect(Collectors.groupingBy(TreeNode::getParentId));

        // 设置子节点
        nodes.forEach(node -> {
            List<T> children = childrenMap.get(node.getId());
            if (children != null) {
                children.sort(Comparator.comparing(TreeNode::getSort));
                node.setChildren(children);
            }
        });

        // 返回顶级节点
        return nodes.stream()
                .filter(node -> node.getParentId() == 0)
                .sorted(Comparator.comparing(TreeNode::getSort))
                .collect(Collectors.toList());
    }
}